package com.gs.synedocket.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;

import androidx.core.content.FileProvider;
import androidx.exifinterface.media.ExifInterface;

import com.gs.synedocket.R;
import com.gs.synedocket.constant.AllConstants;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

public class PhotoUtil {
    private static volatile PhotoUtil instance;

    public PhotoUtil() {
    }

    public static PhotoUtil getInstance() {
        if (instance == null) {
            synchronized (PhotoUtil.class) {
                if (instance == null) {
                    instance = new PhotoUtil();
                }
            }
        }
        return instance;
    }

    public String imgUrl;

    /**
     * 跳转至相机
     *
     * @param activity
     */
    public void toCamera(final Activity activity) {
        if (PermissionUtil.addPermission(activity, new String[]{Manifest.permission.CAMERA},
                AllConstants.PIC_CAMERA)) {
            if (FileUtils.getInstance().hasSdCard()) {
                PackageManager pm = activity.getPackageManager();
                if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA) || pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)) {
                    try {
                        File photoFile = new File(activity.getExternalCacheDir(), System.currentTimeMillis() + ".jpeg");
                        if (photoFile.exists()) {
                            photoFile.delete();
                        }
                        photoFile.createNewFile();
                        imgUrl = photoFile.getAbsolutePath();
                        Uri imageUri;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            imageUri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".provider", photoFile);
                        } else {
                            imageUri = Uri.fromFile(photoFile);
                        }
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                        activity.startActivityForResult(intent, AllConstants.PIC_CAMERA);
                    } catch (Exception e) {
                        ToastUtil.showToast(R.string.no_camera);
                    }
                }
            }
        }
    }

    public Bitmap rotatingPic(int angle, Bitmap bitmap) {
        Bitmap returnBmp = null;
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        try {
            returnBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        } catch (Exception e) {
        }
        if (returnBmp == null) {
            returnBmp = bitmap;
        }

        if (bitmap != null) {
            bitmap.recycle();
        }

        return returnBmp;
    }

    private Camera.CameraInfo info;
    private int angle;

    public int getAngle() {
        try {
            ExifInterface exifInterface = new ExifInterface(imgUrl);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation){
                case ExifInterface.ORIENTATION_ROTATE_90:
                    angle = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    angle = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    angle = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return angle;
    }

    public Bitmap resizeImage(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);//此时返回bm为空
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (w / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (h / hh);
        }
        if (be == 1) {
            be += 1;
        }
        newOpts.inSampleSize = be;//设置缩放比例
        // 设置图片可以缩小
        newOpts.inScaled = true;
        int calSize = Math.min(h, w);
        newOpts.inTargetDensity = (int) ((ww*newOpts.inDensity)/(calSize/newOpts.inSampleSize));
        newOpts.inJustDecodeBounds = false;
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return bitmap;//压缩好比例大小后再进行质量压缩
    }

    public String bitmapToUrl(Context context, Bitmap bitmap) {
        FileOutputStream fops = null;
        String path;
        File saveFile = FileUtils.getInstance().createFile(context, "SynEDocket" + DateUtil.DateTimeToStr(new Date(), "yyyyMMdd_HHmmss") + ".jpg");
        path = saveFile.getAbsolutePath();
        try {
            fops = new FileOutputStream(path);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fops);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fops != null) {
                    fops.flush();
                    fops.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return path;
    }


    public String handlePhoto(Context context){
        int angle = getAngle();
        String url;
        if (angle == 0) {
            url = imgUrl;
        } else {
            Bitmap bitmap = PhotoUtil.getInstance().rotatingPic(PhotoUtil.getInstance().getAngle(), BitmapFactory.decodeFile(imgUrl));
            url = ImageUtil.bitmapToUrl(context, bitmap);
        }
        Bitmap bitmap = PhotoUtil.getInstance().resizeImage(url);
        url = PhotoUtil.getInstance().bitmapToUrl(context, bitmap);
        return url;
    }


    /**
     * 跳转至图库
     *
     * @param activity
     */
    public void toGallery(final Activity activity) {
        if (PermissionUtil.addPermission(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE}, AllConstants.PIC_GALLERY)) {
            try {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                activity.startActivityForResult(intent, AllConstants.PIC_GALLERY);
            } catch (Exception e) {
                ToastUtil.showToast(R.string.no_gallery);
            }
        }
    }
}
